package DBLayer;
import ModelLayer.Group;
import java.sql.*;
import java.util.ArrayList;

public class DBGroup {
    // <editor-fold defaultstate="collapsed" desc="Attributes & Constructors">
    private Connection conn;

    public DBGroup() {
        conn = SQLConnector.getInstance().getConnection();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="SQL SELECT Methods">
    public Group getGroupByID(int id) {
        return selectSingle("SELECT `id_group`, `reduction`, UNIX_TIMESTAMP(`date_add`) AS `date_add`, UNIX_TIMESTAMP(`date_upd`) AS `date_upd`, `name` FROM `ps_group` LEFT JOIN `ps_group_lang` USING (`id_group`) WHERE (`id_lang` = " + Constants.DEFAULT_LANGUAGE + " OR `id_lang` IS NULL) AND `id_group` = " + id + " LIMIT 0, 1;");
    }

    public ArrayList<Group> getGroupList() {
        return selectMultiple("SELECT `id_group`, `reduction`, UNIX_TIMESTAMP(`date_add`) AS `date_add`, UNIX_TIMESTAMP(`date_upd`) AS `date_upd`, `name` FROM `ps_group` LEFT JOIN `ps_group_lang` USING (`id_group`) WHERE `id_lang` = " + Constants.DEFAULT_LANGUAGE + " OR `id_lang` IS NULL ORDER BY `id_group` ASC;");
    }

    public ArrayList<Integer> getGroupIDsByCustomerID(int id) {
        return selectIDs("SELECT `id_group` FROM `ps_customer_group` WHERE `id_customer` = " + id + " ORDER BY `id_group` ASC;");
    }

    private Group selectSingle(String sqlStatement) {
        Statement stmt = null;
        ResultSet result = null;
        Group group = new Group();

        try {
            stmt = conn.createStatement();
            result = stmt.executeQuery(sqlStatement);

            if (result.next()) {
                group = buildGroup(result);
            }
            System.out.println("Fetching Group Object");
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                result = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
        return group;
    }

    private ArrayList<Group> selectMultiple(String sqlStatement) {
        Statement stmt = null;
        ResultSet result = null;
        ArrayList<Group> groups = new ArrayList<Group>();

        try {
            stmt = conn.createStatement();
            result = stmt.executeQuery(sqlStatement);

            while (result.next()) {
                Group group = new Group();
                group = buildGroup(result);
                groups.add(group);
            }
            System.out.println("Fetching Group List");
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                result = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
        return groups;
    }

    private ArrayList<Integer> selectIDs(String sqlStatement) {
        Statement stmt = null;
        ResultSet result = null;
        ArrayList<Integer> ids = new ArrayList<Integer>();

        try {
            stmt = conn.createStatement();
            result = stmt.executeQuery(sqlStatement);

            while (result.next()) {
                ids.add(result.getInt("id_group"));
            }
            System.out.println("Fetching Group ID List");
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                result = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
        return ids;
    }

    private Group buildGroup(ResultSet result) {
        DBCustomer dbCustomer = new DBCustomer();
        Group group = new Group();
        try {
            group.setIDGroup(result.getInt("id_group"));
            group.setReduction(result.getFloat("reduction"));
            group.setDateAdd(result.getInt("date_add"));
            group.setDateUpd(result.getInt("date_upd"));
            group.setName(result.getString("name"));
            group.setCustomerIDs(dbCustomer.getCustomerIDsByGroupID(result.getInt("id_group")));

        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
        return group;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="SQL INSERT, UPDATE & DELETE Methods">
    public int addGroup(Group group) {
        int returnID = 0;
        Statement stmt = null;
        ResultSet result = null;

        String query = "INSERT INTO `ps_group_lang` (`id_group`, `id_lang`, `name`) "
                + "VALUES (" + group.getIDGroup() + ", " + Constants.DEFAULT_LANGUAGE + ", '" + group.getName() + "');";

        query += "INSERT INTO `ps_group` (`id_group`, `reduction`, `date_add`, `date_upd`) "
                + "VALUES (" + group.getIDGroup() + ", " + group.getReduction() + ", FROM_UNIXTIME(" + group.getDateAdd() + "), FROM_UNIXTIME(" + group.getDateUpd() + "));";

        try {
            stmt = conn.createStatement();
            stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
            result = stmt.getGeneratedKeys();
            if (result.next()) {
                returnID = result.getInt(1);
            }
            System.out.println("Added Group ID " + returnID);
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                result = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
        return returnID;
    }

    public int updateGroup(Group group, int id) {
        int returnID = 0;
        Statement stmt = null;
        String query = "UPDATE `ps_group` SET "
                + "`id_group`       = "  + group.getIDGroup()   + ", "
                + "`reduction`      = "  + group.getReduction() + ", "
                + "`date_add`       = FROM_UNIXTIME("  + group.getDateAdd()   + "), "
                + "`date_upd`       = FROM_UNIXTIME("  + group.getDateUpd()   + ") "
                + "WHERE `id_group` = " + id + " LIMIT 1; ";

        query += "UPDATE `ps_group_lang` SET "
                + "`id_group`       = "  + group.getIDGroup() + ", "
                + "`name`           = '" + group.getName() + "' "
                + "WHERE `id_lang` = " + Constants.DEFAULT_LANGUAGE + " AND `id_group` = " + id + " LIMIT 1;";

        try {
            stmt = conn.createStatement();
            stmt.executeUpdate(query);
            returnID = group.getIDGroup();
            System.out.println("Updated Group ID " + id);
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
        return returnID;
    }

    public void deleteGroup(int id) {
        Statement stmt = null;

        try {
            stmt = conn.createStatement();
            stmt.executeUpdate("DELETE FROM `ps_group` WHERE `id_group` = " + id + " LIMIT 1; DELETE FROM `ps_group_lang` WHERE `id_lang` = " + Constants.DEFAULT_LANGUAGE + " AND `id_group` = " + id + " LIMIT 1;");
            System.out.println("Deleted Group ID " + id);
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("SQLException: " + e.getMessage());
                    System.out.println("SQLState: " + e.getSQLState());
                    System.out.println("VendorError: " + e.getErrorCode());
                }
                stmt = null;
            }
        }
    }
    // </editor-fold>
}
